<template>
  <div class="checkin-container">
    <div class="sign-in">
      <div class="sign-in-top">
        <img class="sign-in-bg"
             src="https://img.wifenxiao.com/h5-wfx/images/activity/sign-in-top_img.png"
             alt />
        <div class="btn-box">
          <div class="rule point-detail" @click="JumpName('point')">{{point_name}}明细</div>
          <div class="rule"
              @click="clickPointRule">{{point_name}}规则</div>
        </div>
        <div class="sign-message">
          <span>{{points?points:'0'}}</span>
          <span>我的{{point_name}}</span>
        </div>
      </div>

      <div class="sign-in-body"
           id="calendar"></div>
      <div class="sign-left"
           v-if="is_checkin">
        <div class="sign-btn sign-before"
             v-if="!uid">
          <p>立即签到</p>
        </div>
        <div v-else>
          <div class="sign-btn btn sign-after"
                v-if="has_checkin">
            <p>今日已签到</p>
          </div>
          <div class="sign-btn btn sign-before"
                v-else>
            <p>立即签到</p>
          </div>
        </div>
      </div>
      <div class="sign-left"
           v-else>
        <div class="sign-btn sign-btn-before">
          <p>签到未开启</p>
        </div>
      </div>
      <!-- 积分规则弹窗 -->
      <van-popup v-model="showRegulation"
                 class="masklayer">
        <img src="https://img.wifenxiao.com/h5-wfx/images/activity/helping_popup_close2.png"
             class="close"
             @click="clickCloseRegulation" />
        <div class="regulation">
          <dl>
            <dd class="regulation-text">
              活动规则
            </dd>
            <div class="overflow">
              <dd v-if="checkin_type==1">
                <div>
                  <b>1</b>
                  <span>每天签到可获得{{nowday_points}}{{point_name}}的奖励</span>
                </div>
              </dd>
              <dd v-for="(row,index) in checkin_rules"
                  :key="index">
                <div>
                  <b v-if="checkin_type==1">{{index + 2}}</b>
                  <b v-else>{{index + 1}}</b>
                  <span>连续签到{{row.num}}天奖励{{row.points}}{{point_name}}</span>
                </div>
              </dd>
              <dd v-if="checkin_rules">
                <div>
                  <b v-if="checkin_type==1">{{count_rules + 2}}</b>
                  <b v-else>{{count_rules + 1}}</b>
                  <span>其中签到中断1天签到将重新计算</span>
                </div>
              </dd>

              <dd v-if="checkin_type==2">
                <div>
                  <b>{{count_rules + 2}}</b>
                  <span>{{count_rules}}天一循环</span>
                </div>
              </dd>
              <dd class="regulation-text-bottom">
                <p>最终解释权归本公司所有</p>
              </dd>
            </div>
          </dl>
        </div>
      </van-popup>
      <!-- 签到成功弹窗 -->
      <van-popup v-model="showSignPop"
                 class="sign-pop">
        <div class="sign-pop-con">
          <div class="pop-center">
            <h4 class="title">签到成功</h4>
            <img src="https://img.wifenxiao.com/h5-wfx/images/activity/pop_ok.png"
                 alt />
            <span v-if="points>0"
                  class="pop-point">
              恭喜获得
              <i id="points">{{popPoints}}</i>
              {{point_name}}
            </span>
            <span class="pop-num">
              已连续签到
              <i id="check_num">{{popNum}}</i>天，继续加油～
            </span>
            <!-- onClick="javascript :history.back(-1);"  -->
            <a class="sign-over red-gra-btn"
               href="javascript:;"
               @click="clickCloseSignPop">明天再来</a>
            <img class="sign-close"
                 src="https://img.wifenxiao.com/h5-wfx/images/activity/helping_popup_close2.png"
                 alt
                 @click="clickCloseSignPop" />
          </div>
        </div>
      </van-popup>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { getCheckinInfo, checkinDo } from '@/api/user/member/memberApi'
import Store from '@/utils/store'
import { mpShare } from '@/utils/utils'
import small from '@/smallapp/small'

export default Vue.extend({
  components: {},
  data() {
    return {
      calSignImged: 'https://img.wifenxiao.com/h5-wfx/images/activity/cal_sign_arred.png',
      calSignImg: 'https://img.wifenxiao.com/h5-wfx/images/activity/cal_sign_arr.png',
      is_checkin: '1',
      uid: '',
      has_checkin: 0,
      point_name: '积分',
      points: '',
      avatar: '',
      nickname: '',
      serial_checkin_num: '',
      checkin_type: '',
      nowday_points: '',
      checkin_rules: [
        {
          num: '22',
          points: '2'
        },
        {
          num: '22',
          points: '2'
        },
        {
          num: '22',
          points: '2'
        }
      ],
      count_rules: '',
      countheckday: '', // 已签到日期
      demoEvents: [],
      curYear: '',
      curMonth: '',
      showRegulation: false,
      showSignPop: false,
      popPoints: '',
      popNum: '',
      current_time: '',
      code: ''
    }
  },
  methods: {
    JumpName(name, data) {
      this.$JumpName(this, name, data)
    },
    init() {
      const vueThis = this
      this.uid = this.$store.getters.pid || Store.fetchLocal('uid')
      this.$loadingWrap.show()
      setTimeout(() => {
        this.$loadingWrap.close()
      }, 10000)
      getCheckinInfo().then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          const sid = small.globalData.shopId
          const pid = small.wxCache('global_login_info') ? small.wxCache('global_login_info').uid : '0'
          const option = {
            title: '每日签到领奖',
            shareParam: `sid=${sid}&pid=${pid}`,
          }
          mpShare (true, true, '/user/pages/checkin/index', option, '/checkin')
          const resData = res.data
          this.is_checkin = resData.is_checkin
          this.has_checkin = resData.has_checkin
          this.point_name = resData.point_name || '积分'
          this.points = resData.points
          this.avatar = resData.avatar
          this.nickname = resData.nickname
          this.serial_checkin_num = resData.serial_checkin_num
          this.checkin_type = resData.checkin_type
          this.nowday_points = resData.nowday_points
          this.checkin_rules = resData.checkin_rules
          this.count_rules = resData.count_rules
          this.countheckday = resData.countheckday
          this.current_time = resData.current_time
          this.code = resData.code

          var y = this.countheckday.substring(1, this.countheckday.length - 1).split(',')
          const signList = []
          for (var i = 0; i < y.length; i++) {
            var obj = {}
            obj.signDay = y[i]
            signList.push(obj)
          }
          const localDate = new Date()
          const serial_checkin_num = this.serial_checkin_num
          const calUtil = {
            /**
             * 当前年月,用于签到时的判断
             */
            eventName: 'load',
            // 初始化日历
            init: function(signList) {
              calUtil.setMonthAndDay()
              calUtil.draw(signList)
              calUtil.bindEnvent()
            },
            draw: function(signList) {
              // 绑定日历
              var str = calUtil.drawCal(calUtil.showYear, calUtil.showMonth, signList)
              // $('#calendar').html(str)
              document.getElementById('calendar').innerHTML = str
              // 绑定日历表头
              if (parseInt(calUtil.showMonth) < 10) {
                calUtil.showMonth = '0' + parseInt(calUtil.showMonth)
              }
              var calendarName = calUtil.showYear + '年' + calUtil.showMonth + '月' + calUtil.showDate + '日'
              // $('.calendar_month_span').html(calendarName)
              document.getElementsByClassName('calendar_month_span')[0].innerHTML = calendarName
            },

            /**
             * 绑定事件
             */
            bindEnvent: function() {
              if (calUtil.showMonth < 10) {
                calUtil.showMonth = calUtil.showMonth.substr(-1, 1)
              }
              if (calUtil.showDate < 10) {
                calUtil.showDate = calUtil.showDate.substr(-1, 1)
              }
              let tdArr = document.querySelectorAll('td')
              tdArr.forEach(function(item,index) {
                item.onclick = function() {
                  if (vueThis.has_checkin == 1) {
                    vueThis.$Error('今日已经签到')
                  } else {
                    if (localDate.getFullYear() == calUtil.showYear && localDate.getMonth() + 1 == calUtil.showMonth && localDate.getDate() == calUtil.showDate) {
                      if (vueThis.is_checkin == 1) {
                        if ((this.innerText || this.textContent) == localDate.getDate()) {
                          var code = vueThis.code
                          // var date = $(this).data('index')
                          vueThis.$loadingWrap.show()
                          setTimeout(() => {
                            vueThis.$loadingWrap.close()
                          }, 10000)
                          const params = {
                            check_code: code,
                            ischeckin: 1
                          }
                          checkinDo(params).then(res => {
                            vueThis.$loadingWrap.close()
                            if (res.status == 1) {
                              vueThis.showSignPop = true
                              vueThis.popPoints = res.data.points
                              vueThis.popNum = res.data.serial_checkin_num
                            } else {
                              vueThis.$Error(res.msg)
                            }
                          })
                        }
                      }
                    } else {
                      $.Error('签到非法,请修改本地时间')
                    }
                  }
                }
              })
              var istrue = true
              document.querySelectorAll('.sign-btn')[0].addEventListener('click', function() {
                if (istrue) {
                  if (vueThis.has_checkin == 1) {
                    vueThis.$Error('今日已经签到')
                  } else {
                    istrue = false
                    if (localDate.getFullYear() == calUtil.showYear && localDate.getMonth() + 1 == calUtil.showMonth && localDate.getDate() == calUtil.showDate) {
                      // var dc = localDate.getDate()
                      var code = vueThis.code
                      vueThis.$loadingWrap.show()
                      setTimeout(() => {
                        vueThis.$loadingWrap.close()
                      }, 10000)
                      const params = {
                        check_code: code,
                        ischeckin: 1
                      }
                      checkinDo(params).then(res => {
                        vueThis.$loadingWrap.close()
                        if (res.status == 1) {
                          vueThis.showSignPop = true
                          vueThis.popPoints = res.data.points
                          vueThis.popNum = res.data.serial_checkin_num
                          // vueThis.init()
                        } else {
                          vueThis.$Error(res.msg)
                        }
                      })
                    } else {
                      $.Error('签到非法,请修改本地时间')
                    }
                    setTimeout(function() {
                      istrue = true
                    }, 2000)
                  }
                }
              })
            },

            /**
             * 获取当前选择的年月
             */
            setMonthAndDay: function() {
              let nowMonth = ''
              switch (calUtil.eventName) {
                case 'load':
                  /**
                     * 用于创建初始化日历
                     * @type {string}
                     */
                  calUtil.showYear = vueThis.current_time.substr(0, 4) * 1
                  calUtil.showMonth = vueThis.current_time.substr(4, 2)
                  calUtil.showDate = vueThis.current_time.substr(6, 2)
                  break
                case 'prev':
                  nowMonth = document.getElementsByClassName("calendar_month_span")[0].innerHTML.split('年')[1].split('月')[0]
                  calUtil.showMonth = parseInt(nowMonth) - 1
                  if (calUtil.showMonth == 0) {
                    calUtil.showMonth = 12
                    calUtil.showYear -= 1
                  }
                  break
                case 'next':
                  nowMonth = document.getElementsByClassName("calendar_month_span")[0].innerHTML.split('年')[1].split('月')[0]
                  calUtil.showMonth = parseInt(nowMonth) + 1
                  if (calUtil.showMonth == 13) {
                    calUtil.showMonth = 1
                    calUtil.showYear += 1
                  }
                  break
              }
            },

            /**
             * 获取当前月日期数
             */
            getDaysInmonth: function(iMonth, iYear) {
              var dPrevDate = new Date(iYear, iMonth, 0)
              return dPrevDate.getDate()
            },

            /**
             * 描绘当前月日历排序
             * return: aMonth
             **/
            bulidCal: function(iYear, iMonth) {
              var aMonth = []
              aMonth[0] = new Array(7)
              aMonth[1] = new Array(7)
              aMonth[2] = new Array(7)
              aMonth[3] = new Array(7)
              aMonth[4] = new Array(7)
              aMonth[5] = new Array(7)
              aMonth[6] = new Array(7)
              var dCalDate = new Date(iYear, iMonth - 1, 1)
              var iDayOfFirst = dCalDate.getDay()
              var iDaysInMonth = calUtil.getDaysInmonth(iMonth, iYear)
              var iVarDate = 1
              var d, w
              aMonth[0][0] = '日'
              aMonth[0][1] = '一'
              aMonth[0][2] = '二'
              aMonth[0][3] = '三'
              aMonth[0][4] = '四'
              aMonth[0][5] = '五'
              aMonth[0][6] = '六'
              for (d = iDayOfFirst; d < 7; d++) {
                aMonth[1][d] = iVarDate
                iVarDate++
              }

              for (w = 2; w < 7; w++) {
                for (d = 0; d < 7; d++) {
                  if (iVarDate <= iDaysInMonth) {
                    aMonth[w][d] = iVarDate
                    iVarDate++
                  }
                }
              }
              return aMonth
            },

            /**
             * 判断是否已签到
             * signList: 已签到日
             * day: 当前月份所有日
             * return: signed
             **/
            ifHasSigned: function(signList, day) {
              var signed = false
              if (!day) {
                return false
              }
              for (var i=0,l=signList.length;i<l;i++) {
                if (Number(signList[i].signDay) == Number(day)) {
                  signed = true
                }
              }
              return signed
            },

            /**
             * 创建签到日历
             * iYear, iMonth: 当前年月
             * signList: 已签到日期
             **/
            drawCal(iYear, iMonth, signList) {
              var myMonth = calUtil.bulidCal(iYear, iMonth)
              var htmls = []
              htmls.push("<div class='sign_main' id='sign_layer'>")
              htmls.push("<div class='calendar_month_span'></div>")
              htmls.push('<div class="pop_num">已连续签到<span>' + serial_checkin_num + '</span>天</div>')
              htmls.push('</div>')
              htmls.push("<div class='' id='sign_cal'>")
              htmls.push('<table border="0" cellpadding="0" cellspacing="0">')
              htmls.push('<thead>')
              htmls.push('<tr>')
              for (d = 0; d < 7; d++) {
                htmls.push('<th>' + myMonth[0][d] + '</th>')
              }
              htmls.push('</tr>')
              htmls.push('</thead>')
              htmls.push('<body>')
              var d, w
              for (w = 1; w < 7; w++) {
                if (w == 6 && myMonth[w][0] == undefined) { break }
                htmls.push('<tr>')
                for (d = 0; d < 7; d++) {
                  // // console.log(signList)
                  // // console.log(myMonth[w][d])
                  var ifHasSigned = calUtil.ifHasSigned(signList, myMonth[w][d])
                  if (ifHasSigned) {
                    htmls.push("<td class='" + myMonth[w][d] + " on' data-index='" + myMonth[w][d] + "'>" + '<span>' + (!isNaN(myMonth[w][d]) ? myMonth[w][d] : '') + '</span>' + '<i>已签到</i>' + "<img src='" + vueThis.calSignImg + "'/><img src='" + vueThis.calSignImged + "'/></td>")
                  } else {
                    htmls.push("<td class='" + myMonth[w][d] + "' data-index='" + myMonth[w][d] + "'>" + (!isNaN(myMonth[w][d]) ? myMonth[w][d] : ' ') + '</td>')
                  }
                }
                htmls.push('</tr>')
              }
              htmls.push('</table>')
              htmls.push('</body></div>')
              htmls.push('</div>')

              return htmls.join('')
            }
          }
          calUtil.init(signList)
          let onItem = document.querySelectorAll('.checkin-container .on')
          // console.log(onItem,'all span')
          if (onItem) {
            let lastOn = onItem[onItem.length - 1]
            lastOn.querySelectorAll('span')[0].style.color = '#ffffff'
            lastOn.querySelectorAll('i')[0].style.display = 'block'
            lastOn.querySelectorAll('img')[0].style.display = 'block'
            lastOn.querySelectorAll('img')[1].style.display = 'none'
          }
          
        } else {
          this.$Error(res.msg)
        }
      })
    },
    // 打开积分规则
    clickPointRule() {
      this.showRegulation = true
    },
    // 关闭积分规则
    clickCloseRegulation() {
      this.showRegulation = false
    },
    // 签到成功弹窗
    clickCloseSignPop() {
      this.showSignPop = false
      this.init()
    }
  },
  created() {
    const date = new Date()
    this.curYear = date.getFullYear()
    this.curMonth = date.getMonth() < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
    this.count_rules = this.checkin_rules.length
    this.init()
  }
})
</script>

<style lang="scss">
.miniprogram-root{
  .h5-body{
    background: #fff;
  }
}
.checkin-container {
  img {
    display: block;
  }
  .sign-in-body {
    width: 700px;
    position: relative;
    top: -222px;
    left: 50%;
    transform: translateX(-50%);
    overflow: hidden;
    padding-top: 210px;
    background: url("https://img.wifenxiao.com/h5-wfx/images/activity/calendar_bg.png") top/contain
      no-repeat;
    .sign_main {
      position: relative;
      overflow: hidden;
      padding: 5px 30px 0;
      .calendar_month_span {
        float: left;
        font-size: 28px;
        color: #666666;
        line-height: 28px;
      }
      .pop_num {
        float: right;
        font-size: 26px;
        line-height: 28px;
        color: #666666;
        span {
          font-size: 36px;
          color: #f5102b;
          margin: 0 5px;
        }
      }
    }

    table {
      width: 100%;
      background: #fff;
      border-radius: 0 0 20px 20px;
      tbody {
        padding: 0 0 20px;
        display: inline-block;
        width: 100%;
        background: #fff;
        tr {
          height: 80px;
          line-height: 80px;
          color: #333333;
        }
        .on {
          span {
            color: #333333;
          }
          img {
            display: none;
            &:last-child {
              display: block;
            }
          }
        }
      }
      thead {
        height: 68px;
        display: block;
        line-height: 68px;
        margin-top: 40px;
        background: rgba(255, 247, 248, 1);
        tr {
          color: #f20b22;
        }
      }
      tr {
        display: flex;
        display: -webkit-box;
        display: -webkit-flex;

        flex-direction: row;
        -webkit-flex-direction: row;
        -moz-flex-direction: row;

        justify-content: space-around;
        -webkit-justify-content: space-around;
        -moz-justify-content: space-around;

        width: 100%;
        font-size: 26px;
      }
      td {
        text-align: center;
        position: relative;
        width: 14.285%;
      }
      span {
        position: absolute;
        width: 100%;
        color: #fff;
        z-index: 4;
        text-align: center;
        left: 0;
        font-size: 26px;
      }
      i {
        display: none;
        width: 100%;
        position: absolute;
        color: #f20b22;
        font-size: 20px;
        text-align: center;
        top: 40px;
        left: 0;
      }
      img {
        height: 46px;
        width: 46px;
        position: absolute;
        left: 51%;
        top: 50%;
        transform: translate(-50%, -50%);
        z-index: 1;
        &:last-child {
          width: 27px;
          // height: 19px;
          top: 75px;
        }
      }
    }
  }
  .sign-in {
    height: 100%;
    .sign-in-top {
      position: relative;
      background-color: #fff;
      .sign-in-bg {
        width: 100%;
      }
      .btn-box{
        position: absolute;
        top: 20px;
        right: 28px;
        z-index: 2;
        font-size:0;
      }
      .rule {
        display:inline-block;
        font-size: 24px;
        color: #542b01;
        line-height: 43px;
        margin-left: 14px;
        padding: 0 20px;
        background: url("https://img.wifenxiao.com/h5-wfx/images/activity/btn_bg.png") top/100% 100%
          no-repeat;
      }
      .sign-in-head {
        position: absolute;
        z-index: 2;
        left: 0;
        right: 0;
        margin: 0 auto;
        top: 92px;
        text-align: center;
        .user-logo {
          width: 138px;
          margin: 0 auto;
          display: block;
          border-radius: 50%;
          overflow: hidden;
          img {
            width: 138px;
            height: 138px;
          }
        }
        .logon-message {
          color: #fff;
          text-align: center;
          margin-top: 20px;
          display: inline-block;
          p {
            width: 250px;
            line-height: 1.5;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .logon-message-top {
            font-size: 26px;
          }
        }
      }
    }
    .sign-message {
      position: absolute;
      z-index: 2;
      left: 0;
      right: 0;
      margin: 0 auto;
      top: 300px;
      width: 238px;
      span {
        display: block;
        text-align: center;
        font-size: 24px;
        color: #180000;
        line-height: 50px;
        &:first-child {
          font-weight: bold;
          font-size: 40px;
          color: #321900;
        }
      }
    }
    //签到成功弹窗
    .sign-pop {
      width: 600px;
      padding-bottom: 102px;
      background: transparent;
      .sign-pop-con {
        position: relative;
        height: 716px;
        background: #fff;
        border-radius: 20px;
        .pop-center {
          position: absolute;
          height: 100%;
          width: 100%;
          .title {
            width: 430px;
            height: 149px;
            margin: 38px auto 0;
            background: url("https://img.wifenxiao.com/h5-wfx/images/activity/popon_title.png")
              center/cover no-repeat;
            font-size: 36px;
            text-align: center;
            font-weight: bold;
            color: #fff;
            padding-top: 18px;
            box-sizing: border-box;
          }
          img {
            display: block;
            width: 200px;
            margin: 0 auto;
            height: 200px;
          }
          span {
            display: block;
            font-size: 32px;
            line-height: 58px;
            color: #333333;
            text-align: center;
            margin: 0 atuo;
            &.pop-point {
              font-size: 32px;
              font-weight: bold;
              i {
                color: #ffae00;
              }
            }
            &.pop-num {
              font-size: 28px;
              i {
                color: #f30c22;
              }
            }
          }
          .sign-over {
            display: block;
            width: 436px;
            line-height: 92px;
            border-radius: 46px;
            margin: 60px auto;
            text-align: center;
            color: #fff;
            font-size: 32px;
          }
          .sign-close {
            position: absolute;
            left: 0;
            right: 0;
            margin: 0 auto;
            width: 60px;
            height: auto;
            bottom: -100px;
          }
        }
      }
    }
  }
  .sign-left {
    margin-top: -192px;
    .sign-btn {
      width: 600px;
      height: 92px;
      background: linear-gradient(
        -90deg,
        rgba(233, 1, 4, 1),
        rgba(254, 27, 73, 1)
      );
      box-shadow: 0px 10px 16px 0px rgba(235, 3, 9, 0.2);
      border-radius: 46px;
      margin: 0 auto;
      p {
        color: #fff;
        line-height: 92px;
        text-align: center;
        font-size: 32px;
      }
      &.sign-after,
      .sign-btn-before {
        opacity: 0.6;
      }
    }
  }
  // 积分规则弹窗
  .masklayer {
    overflow: visible;
    width: 600px;
    height: 552px;
    background: url("https://img.wifenxiao.com/h5-wfx/images/activity/rule_bg.png") center/cover
      no-repeat;
    border-radius: 20px;
    .close {
      position: absolute;
      bottom: -116px;
      left: 50%;
      transform: translateX(-50%);
      display: block;
      width: 76px;
      height: 76px;
      z-index: 10;
    }
    .regulation {
      overflow: hidden;
      max-height: 100%;
      min-height: 30%;
      dl {
        width: 100%;
        .overflow {
          height: 380px;
          overflow-y: auto;
          overflow-x: hidden;
        }
        dd {
          width: 100%;
          color: #585858;
          font-family: "微软雅黑";
          &.regulation-text {
            font-size: 36px;
            font-weight: bold;
            color: rgba(243, 12, 34, 1);
            margin: 0 auto;
            text-align: center;
            padding: 60px 0 30px;
          }
          &.regulation-text-bottom {
            width: 540px;
            border-top: 2px dashed #999;
            box-sizing: border-box;
            margin: 50px auto 0;
            position: relative;
            p {
              width: 300px;
              position: absolute;
              background: #fff;
              left: 50%;
              transform: translate(-50%, -50%);
              text-align: center;
              font-size: 26px;
              color: #999999;
            }
          }
          div {
            width: 100%;
            box-sizing: border-box;
            margin: 0 auto;
            line-height: 72px;
            padding-left: 70px;
            b {
              display: inline-block;
              width: 41px;
              line-height: 41px;
              background: url("https://img.wifenxiao.com/h5-wfx/images/activity/clum_bg.png")
                center/cover no-repeat;
              text-align: center;
              color: #fff;
              font-size: 28px;
            }
            span {
              color: #333333;
              font-size: 28px;
            }
          }
        }
      }
    }
  }
}
</style>
